from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import redis
import uuid
import configparser

# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')

# 配置 Redis
redis_host = config['redis']['host']
redis_port = config['redis']['port']
redis_db = config['redis']['db']
redis_password = config['redis']['password']  # 读取 Redis 密码
r = redis.Redis(host=redis_host, port=int(redis_port), db=int(redis_db), password=redis_password)

app = FastAPI()

class SubmitTaskRequest(BaseModel):
    command: str
    machine_id: str

@app.post("/submit_task/")
def submit_task(request: SubmitTaskRequest):
    task_id = str(uuid.uuid4())
    task = {
        'id': task_id,
        'command': request.command,
        'machine_id': request.machine_id,
        'status': 'queued',
        'result': ''
    }
    r.hmset(task_id, mapping=task)
    r.lpush('task_queue', task_id)
    return {"task_id": task_id}

@app.get("/task_status/{task_id}")
def task_status(task_id: str):
    task = r.hgetall(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    task_decoded = {k.decode(): v.decode() for k, v in task.items()}
    return task_decoded

@app.get("/reset_task/{task_id}")
def reset_task(task_id: str):
    task_data = r.hgetall(task_id)
    if not task_data:
        raise HTTPException(status_code=404, detail="Task not found")

    task = {k.decode(): v.decode() for k, v in task_data.items()}
    task['status'] = 'queued'
    task['result'] = ""

    r.hmset(task_id, task)
    r.lpush("task_queue", task_id)
    return {"message": f"Task {task_id} has been reset and requeued"}

@app.delete("/delete_task/{task_id}")
def delete_task(task_id: str):
    task_data = r.hgetall(task_id)
    if not task_data:
        raise HTTPException(status_code=404, detail="Task not found")
    
    r.delete(task_id)
    return {"message": f"Task {task_id} has been deleted"}